//
//  AFFVCSegmented.m
//  AnyfishApp
//
//  Created by Angel_Yan on 15/9/22.
//  Copyright © 2015年 Anyfish. All rights reserved.
//

#import "AFFVCSegmented.h"

#define ButtonTag 100

@interface AFFVCSegmented ()<UIScrollViewDelegate>
{
    NSInteger indexCur; // 用作判断是否变化的值
    CGFloat _heightBadge;
    
}

// 游标
@property (nonatomic , strong) UIView *viewLine;
@property (nonatomic , retain) UIView *viewLineBg;
@property (nonatomic , retain) NSMutableArray *mArrBtns;
@end


@implementation AFFVCSegmented

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)setupData {
    [super setupData];
    self.arrSegment = [[NSArray alloc] init];
    self.mArrBtns = [[NSMutableArray alloc] init];
    self.color_seg_nor = kSetting.color_666666;
    self.color_seg_sel = KUIColorARGBString(@"1A7FFE");
}

- (void)setup {
    [super setup];

    _heightBadge = 46;
    UIView *segmentScr = [[UIView alloc] initWithFrame:CGRectZero];
    segmentScr.backgroundColor = kSetting.color_ffffff;
    self.segmentScr = segmentScr;
    [self.view addSubview:self.segmentScr];
    [self.segmentScr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(SafeAreaTopHeight);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.equalTo(@(_heightBadge));
    }];
    
    // 游标
    self.viewLine = [[UIView alloc] initWithFrame:CGRectZero];
    self.viewLine.backgroundColor = self.color_seg_sel;
    self.viewLine.layer.cornerRadius = self.viewLine.height/2;
    [self.segmentScr addSubview:self.viewLine];
    
    // 游标约束
    [self.viewLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(100));
        make.left.equalTo(self.segmentScr);
        make.height.equalTo(@(2));
        make.top.equalTo(self.segmentScr).offset(_heightBadge-2);
    }];
    
    
    // 线条
    UIView *vb =[[UIView alloc] initWithFrame:CGRectZero];
    vb.backgroundColor = kSetting.color_Separate;
    self.viewLineBg = vb;
    [self.view addSubview:self.viewLineBg];
    
    // 线条约束
    [self.viewLineBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.segmentScr.mas_left);
        make.right.equalTo(self.segmentScr.mas_right);
        make.top.equalTo(self.segmentScr.mas_bottom);
        make.height.equalTo(@(kSetting.height_Separate));
    }];
    

    //承载 tableView 的scrollView
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor clearColor];
    self.segmentContentScr = scrollView;
    [self.view addSubview:self.segmentContentScr];

    [self.segmentContentScr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.segmentScr);
        make.right.equalTo(self.segmentScr);
        make.width.equalTo(self.view);
        make.top.equalTo(self.viewLineBg.mas_bottom);
        make.bottom.equalTo(self.view);
        ;
    }];
}


- (void)removeSupper {
    self.segmentContentScr.delegate = nil;
    [self.segmentContentScr removeFromSuperview];
    self.segmentContentScr = nil;
    [self.segmentScr removeFromSuperview];
    self.segmentScr = nil;
}

- (void)cleanSelf {
    if(self.hadCleaned)return;
    
    for(UIView *view in self.segmentContentScr.subviews){
        if([view isKindOfClass:[UITableView class]]){
            UITableView *tbv = (UITableView*)view;
            tbv.delegate = nil;
            tbv.dataSource = nil;
        }
        [view removeFromSuperview];
    }
    
    self.segmentContentScr.delegate = nil;
    [self.segmentContentScr removeFromSuperview]; self.segmentContentScr = nil;
    
    [self.segmentScr removeFromSuperview]; self.segmentScr = nil;
    
    self.color_seg_nor = self.color_seg_sel = nil;
    self.arrSegment = nil;
    
    [super cleanSelf];
}

- (void)setArrSegment:(NSArray *)arrSegment {
    if (arrSegment == nil || arrSegment.count == 0) {
        return;
    }
    
    _arrSegment = arrSegment;
    
    // 有多少个绘制多少个
    for (int i = 0; i < _arrSegment.count; i ++) {
        UIButton *btn = [self setBtnWithIndex:i withTitle:_arrSegment[i]];
        [self.segmentScr addSubview:btn];
        [self.mArrBtns addObject:btn];
    }
    [self.mArrBtns mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    // 设置array的垂直方向的约束
    [self.mArrBtns mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segmentScr);
        make.bottom.equalTo(self.segmentScr);
    }];
    //设置 contentSize
    self.type = ESegmentline_long;
}

- (NSArray *)ArrSegment {
    return _arrSegment;
}

- (void)setColor_seg_nor:(UIColor *)color_seg_nor {
    //设置 btn 的默认颜色
    _color_seg_nor = color_seg_nor;
    for (UIView *view in self.segmentScr.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            [(UIButton*)view setTitleColor:color_seg_nor forState:UIControlStateNormal];
        }
    }
}

- (void)setColor_seg_sel:(UIColor *)color_seg_sel {
    _color_seg_sel = color_seg_sel;
    self.viewLine.backgroundColor = color_seg_sel;
    //设置 btn 的默认颜色
    for (UIView *view in self.segmentScr.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            [(UIButton*)view setTitleColor:color_seg_sel forState:UIControlStateSelected];
        }
    }
}

- (void)setType:(AFFSegmentlineType)type {
    _type = type;
    if (_arrSegment.count == 0) {
        return;
    }
     switch (type) {
        case ESegmentline_short:
        {
            [self.viewLine mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(self.segmentScr.mas_width).multipliedBy(1.0/self.mArrBtns.count/2);
                make.left.equalTo(self.segmentScr).offset(self.currentIndex*(SCREEN_WIDTH/self.mArrBtns.count)+SCREEN_WIDTH/self.mArrBtns.count/4);
            }];
        }
            break;
        case ESegmentline_long:
        {
            [self.viewLine mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(self.segmentScr.mas_width).multipliedBy(1.0/self.mArrBtns.count);
                make.left.equalTo(self.segmentScr).offset(self.currentIndex*(SCREEN_WIDTH/self.mArrBtns.count));
            }];
        }
            break;
        default:
            break;
    }
}

- (UIButton *)setBtnWithIndex:(int)index withTitle:(NSString *)title{
    UIButton * btn =[UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = ButtonTag + index;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:kSetting.color_999999 forState:UIControlStateNormal];
    [btn setTitleColor:KUIColorARGBString(@"1A7FFE") forState:UIControlStateSelected];
    btn.titleLabel.font = kSetting.font_15;
    btn.titleLabel.textAlignment = kTextAlignmentCenter;
    [btn addTarget:self action:@selector(selectSegment:) forControlEvents:UIControlEventTouchUpInside];
    if (index == 0){
        btn.selected = YES;
        btn.titleLabel.font = kSetting.font_17;
    }
    return btn;
}

- (void)selectSegment:(UIButton *)sender {
    if(!self.segmentContentScr.scrollEnabled)
        return;
    
    for (UIView *view in self.segmentScr.subviews)
    {
        if ([view isKindOfClass:[UIButton class]])
        {
            if (sender == view) {
                ((UIButton *)view).selected = YES;
                ((UIButton *)view).titleLabel.font = kSetting.font_17;
            }else{
                ((UIButton *)view).selected = NO;
                ((UIButton *)view).titleLabel.font = kSetting.font_15;
            }
        }
    }
    
    NSUInteger index = sender.tag-ButtonTag;
    [self scrollToIndex:index];
}

- (void)scrollToIndex:(NSInteger)index {
    if(self.delegateSeg && [self.delegateSeg respondsToSelector:@selector(segmentWillChangeToIndex:)]){
        [self.delegateSeg segmentWillChangeToIndex:self.currentIndex];
    }
    
    if(indexCur!=index){
        self.currentIndex = index;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.viewLine mas_updateConstraints:^(MASConstraintMaker *make) {
            if (self.type == ESegmentline_short) {
                make.left.equalTo(self.segmentScr).offset(self.currentIndex*(SCREEN_WIDTH/self.mArrBtns.count)+SCREEN_WIDTH/self.mArrBtns.count/4);
            } else {
                make.left.equalTo(self.segmentScr).offset(self.currentIndex*(SCREEN_WIDTH/self.mArrBtns.count));
            }
        }];
        _segmentContentScr.contentOffset = CGPointMake(CGRectGetWidth(_segmentContentScr.frame)*index, _segmentContentScr.contentOffsetY);
    } completion:^(BOOL finished) {
        if(indexCur!=self.currentIndex){
            indexCur = self.currentIndex;
            if(self.delegateSeg && [self.delegateSeg respondsToSelector:@selector(segmentDidChangeToIndex:)]){
                [self.delegateSeg segmentDidChangeToIndex:self.currentIndex];
            }
        }
    }];
}

- (void)setMarginBottom:(CGFloat)marginBottom {
    if(marginBottom>0){
        [self.segmentContentScr mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.viewLineBg).offset(marginBottom);
        }];
    }
}

- (BOOL)isLoading {
    BOOL load = NO;
    for(UIView *view in _mArrSubPage){
        if(view.isLoading){
            load = YES;
            break;
        }
    }
    
    return load;
}

#pragma mark - UIScrollView

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (isTransition) {
        return;
    }

    
    if (scrollView == _segmentContentScr)
    {
        float page = scrollView.contentOffset.x/CGRectGetWidth(scrollView.frame);
        int crtPage = page+0.5;
        if(indexCur!=crtPage)
            self.currentIndex = crtPage;
        
        UIButton *btn = (UIButton *)[self.segmentScr viewWithTag:crtPage+ButtonTag];
        [self.viewLine mas_updateConstraints:^(MASConstraintMaker *make) {
            if (self.type == ESegmentline_short) {
                make.left.equalTo(self.segmentScr).offset(page*(SCREEN_WIDTH/self.mArrBtns.count)+SCREEN_WIDTH/self.mArrBtns.count/4);
            } else {
                make.left.equalTo(self.segmentScr).offset(page*(SCREEN_WIDTH/self.mArrBtns.count));
            }
            
        }];
        if (!btn.selected)
        {
            for (int i=0; i<self.arrSegment.count; i++)
            {
                UIButton *btn = (UIButton *)[self.segmentScr viewWithTag:i+ButtonTag];
                if (crtPage == i) {
                    btn.selected = YES;
                    btn.titleLabel.font = kSetting.font_17;
                }else{
                    btn.selected = NO;
                    btn.titleLabel.font = kSetting.font_15;
                }
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (isTransition) {
        return;
    }

    if(scrollView == _segmentContentScr){
        if(indexCur!=self.currentIndex){
            indexCur = self.currentIndex;
            if(self.delegateSeg && [self.delegateSeg respondsToSelector:@selector(segmentDidChangeToIndex:)]){
                [self.delegateSeg segmentDidChangeToIndex:self.currentIndex];
            }
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    if (isTransition) {
        return;
    }
}


BOOL isTransition = NO;
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    // 总宽度
    isTransition = YES;
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        isTransition = NO;
        [self.segmentContentScr setContentOffset:CGPointMake(self.currentIndex*size.width, 0) animated:NO];
        [self.viewLine mas_updateConstraints:^(MASConstraintMaker *make) {
            if (self.type == ESegmentline_short) {
                make.left.equalTo(self.segmentScr).offset(self.currentIndex*(SCREEN_WIDTH/self.mArrBtns.count)+SCREEN_WIDTH/self.mArrBtns.count/4);
            } else {
                make.left.equalTo(self.segmentScr).offset(self.currentIndex*(SCREEN_WIDTH/self.mArrBtns.count));
            }
        }];
    }];
}

@end
